package com.zsk.okhttp;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Base64;

import com.alibaba.fastjson.JSON;

import okhttp3.Response;
import okhttp3.internal.Util;

public class ResData {

	private Response response;

	public ResData() {

	}

	public ResData(Response response) {
		this.response = response;
	}

	public static ResData of(Response response) {
		return new ResData(response);
	}

	public <T> T toBean(Class<T> clazz) throws IOException {
		return JSON.parseObject(response.body().string(), clazz);
	}

	public <T> T toBean(String json, Class<T> clazz) {
		return JSON.parseObject(json, clazz);
	}

	public String toStr() throws IOException {
		return response.body().string();
	}

	/**
	 * 将响应转换为文件，下载进度监听支持null
	 * 
	 * @param filePath
	 * @param listener 下载进度监听
	 * @return
	 * @date 2020/04/17 10:45:46
	 */
	public boolean toFile(String filePath, PercentListener listener) {
		return toFile(response, filePath, listener);
	}

	public boolean toFile(Response response, String filePath, PercentListener listener) {
		byte[] buf = new byte[1024];
		FileOutputStream fos = null;
		try {
			File file = new File(filePath);
			File dir = file.getParentFile();
			if (dir != null && dir.isDirectory())
				dir.mkdirs();
			InputStream is = response.body().byteStream();
			long total = response.body().contentLength();
			fos = new FileOutputStream(file);
			long sum = 0;
			int progress = 0;
			int len = 0;
			int prePercent = 0;
			while ((len = is.read(buf)) != -1) {
				fos.write(buf, 0, len);
				sum += len;
				progress = (int) (sum * 1.0 / total * 100);
				// update download percent
				if (listener != null && progress > prePercent) {
					listener.process(progress);
					prePercent = progress;
				}
			}
			fos.flush();
			progress = 100;
			if (listener != null && progress > prePercent)
				listener.process(progress);
			return true;
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			Util.closeQuietly(fos);
		}
		return false;
	}

	public byte[] toBytes() throws IOException {
		return response.body().bytes();
	}

	public String toBase64Str() throws IOException {
		return Base64.getEncoder().encodeToString(response.body().bytes());
	}

	public void close() {
		response.close();
	}

	public static interface PercentListener {
		void process(int percent);
	}

}
